from geocoder import ip
from geocoder.ipinfo import IpinfoQuery
from requests import get
from typing import Optional
from rich.table import Table
from rich.console import Console
from utils import (
    config,
    WeatherWarning,
    Unit, Language,
    get_location,
    format_time
)
from utils.type import _WeatherWarning

def weather_warning(
        location: Optional[str]=None,
        language: Language=None,
        unit: Unit=None
    ) -> list[_WeatherWarning] | str:
    """
    Get weather warning for now

    Args:
        location: Location to get weather warning. Default: `None`
        language: Language to get weather warning. Default: `None`
        unit: Unit to get weather warning. Default: `None`

    Returns:
        Weather warning
    """
    # Get location
    if location is None:
        location = 'me'
        g: IpinfoQuery = ip(location, timeout=1)
        loc = ','.join([str(g.latlng[1]), str(g.latlng[0])])
    else:
        loc = get_location(location)
    # Get language and unit
    if language is None:
        language = config.language
    if unit is None:
        unit = config.unit
    # Get qweather api
    base_url = f'{config.base_url}/v7/warning/now?location={loc}&lang={language}&unit={unit}'
    headers = {'Authorization': f'Bearer {config.token}'}
    # Send request and get response in json format
    resp = get(url=base_url, headers=headers)
    result: WeatherWarning = resp.json()
    if 'warning' in result:
        return result['warning']

def print_warning(
        warnings: list[_WeatherWarning] | str,
        unit: Unit=None
    ) -> None:
    """
    Print weather warnings with table

    Args:
        warnings: Weather warnings or an empty string
        unit: Unit. Default: `None`
    """
    # Create Console
    console = Console(width=config.console_width)
    # Get default unit
    if unit is None:
        unit = config.unit
    if len(warnings) > 0:
        for warning in warnings:
            level_color = warning['severityColor'].lower()
            if level_color == 'orange':
                level_color = 'orange1'
            # Create Table
            t = Table(title=warning['title'], header_style='bold')
            t.add_column('时间', style='green')
            t.add_column('级别', style=level_color)
            t.add_column('类型', style=f'bold {level_color}')
            # Add rows
            start_time = format_time(warning['startTime'], '%Y/%m/%d %H:%M')
            end_time = format_time(warning['endTime'], '%Y/%m/%d %H:%M')
            t.add_row(f'{start_time} - {end_time}', warning['level'], warning['typeName'])
            # Print table
            console.print(t)
            console.print('Warning:', style='bold yellow')
            console.print(warning['text'], style='italic orange1')
            if warnings.index(warning) != len(warnings) - 1:
                console.print()
                console.print('─' * config.console_width, style='dim')
                console.print()
    else:
        console.print('[bold red]No weather warning found[/]')
